import axios from 'axios'
// import Qs from 'qs'
import { Loading, Message, Notification } from 'element-ui'
import store from '../store'
import base from '@/utils/index'
import globalConfig from '@/config'

const baseFunc = base()
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 15000 // request timeout
})

// 拦截器loading白名单
const whiteList = ['/service/internal/data']

// 不需要token的列表
const noToken = [
  '/zjec-api/auth/login', // 未处理报警数量
  '/user/ucenter/checkCode'
]

const loginUrl = '/api/zjec-api/auth/login'

let needLoadingRequestCount = 0
let fullLoading
// 登录报错次数
// let loginErrorCount = 0
export const showLoading = () => {
  if (needLoadingRequestCount === 0) {
    fullLoading = Loading.service({
      background: 'rgba(0, 0, 0, .2)',
      text: '加载中',
      spinner: 'el-icon-loading'
    })
  }
  needLoadingRequestCount++
}

export const tryHideLoading = () => {
  if (needLoadingRequestCount <= 0) return
  needLoadingRequestCount--
  if (needLoadingRequestCount === 0) {
    fullLoading.close()
  }
}

service.interceptors.request.use(
  config => {
    if (config.url.startsWith('/classroom')) {
      config.baseURL = '' // 关键：绕过 baseURL
    }
    // 如果没有权限则先进行拦截，权限存在store中，如果没有则往storage中取
    let permission = []
    if (!store.state.apiPermission.length) {
      permission = baseFunc.getUserApiPermission()
      store.commit('setApiPermission', permission)
    } else {
      permission = store.state.apiPermission
    }
    if (config.url.startsWith('/classroom')) {
      config.url = config.url.replace('/gateway/api', '')
    }
    let url = '/inspection' + String(config.url).replace(String(config.baseURL), '')
    if (permission.indexOf(url) < 0 && globalConfig.needApiPermission && loginUrl !== url) {
      Message({
        message: url + '接口没有权限',
        type: 'error'
      })
      return Promise.reject(new Error(config.url + ' has no permission'))
    }
    console.log(config.url, 'config.url')
    const inNotoken = noToken.some(url => config.url.includes(url))
    console.log(inNotoken, config.url)
    if (!inNotoken) {
      config.headers.token = JSON.parse(localStorage.getItem('Standard__Access-Token'))?.value || ''
    }
    if (whiteList.indexOf(config.url) < 0) {
      showLoading()
    }
    // if (process.env.NODE_ENV === 'production') {
    //   if (config.customData && config.customData.baseUrl) {
    //     config.url = config.customData.baseUrl + config.url
    //   } else {
    //     config.url = config.url
    //   }
    // }
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

const err = function (error) {
  tryHideLoading()
  if (error.response) {
    let data = error.response.data
    switch (error.response.status) {
      case 401:
        window.location.reload()
        break
      default:
        Notification.error({
          title: '系统提示',
          message: data.message
        })
        break
    }
  }
  return Promise.reject(error)
}

// http request 拦截器
service.interceptors.response.use(response => {
  if (response.data.code !== 0) {
    if (response.data.code === 200002) {
      window.location.reload()
    } else {
      if (Object.prototype.toString.call(response.data) === '[object Blob]') {
        tryHideLoading()
        return Promise.resolve(response.data)
      } else {
        Notification.error({
          title: '提示',
          message: response.data.msg
        })
        tryHideLoading()
        return Promise.reject(response)
      }
    }
  }
  tryHideLoading()
  const { customData } = response.config
  if (customData && customData.returnResponse) {
    return response
  } else {
    return response.data
  }
}, err)

// post
export function $post (params) {
  return service({
    url: params.url,
    method: 'post',
    data: params.data,
    customData: params.customData,
    timeout: params.timeout
  })
}

// get
export function $get (params) {
  return service({
    url: params.url,
    method: 'get',
    params: params.data,
    customData: params.customData,
    responseType: params.responseType
  })
}

// del方法
export function $del (params) {
  return service({
    url: params.url,
    method: 'delete',
    params: params.data,
    customData: params.customData
  })
}

// del 通过body传递参数
export function $delB (params) {
  return service({
    url: params.url,
    method: 'delete',
    data: params.data,
    customData: params.customData
  })
}

// put
export function $put (params) {
  return service({
    url: params.url,
    method: 'put',
    data: params.data
  })
}

// // 文件下载
// export function $fileDownLoad (params) {
//   return new Promise((resolve, reject) => {
//     service({
//       url: params.url,
//       method: params.method,
//       params: params.data,
//       responseType: 'blob',
//       customData: params.customData
//     })
//       .then(res => {
//         console.log(res,2222222)
//         console.log(res.config)
//         let filename = params.filename
//         let isReturnResponse = res.config.customData && res.config.customData.returnResponse
//         let data = isReturnResponse ? res.data : res
//         if (!filename && isReturnResponse) {
//           // 获取后端返回的文件名
//           let contentDisposition = res.headers['content-disposition']
//           if (contentDisposition) {
//             filename = window.decodeURI(res.headers['content-disposition'].split('=')[1], 'UTF-8')
//           }
//         }
//         let fileReader = new FileReader()
//         fileReader.onload = function () {
//           try {
//             let jsonData = JSON.parse(this.result)
//             if (jsonData.code) {
//               // 说明是普通对象数据，后台转换失败
//               reject(jsonData)
//             }
//           } catch (err) {
//             if (data instanceof Blob) {
//               if (window.navigator.msSaveOrOpenBlob) {
//                 navigator.msSaveBlob(data, filename)
//               } else {
//                 const link = document.createElement('a')
//                 link.href = window.URL.createObjectURL(data)
//                 link.download = filename
//                 link.style.display = 'none'
//                 // 兼容火狐浏览器
//                 document.body.appendChild(link)
//                 const evt = document.createEvent('MouseEvents')
//                 evt.initEvent('click', false, false)
//                 link.dispatchEvent(evt)
//                 document.body.removeChild(link)
//               }
//               resolve({ code: 0 })
//             }
//           }
//         }
//         fileReader.readAsText(data)
//         // resolve(data)
//       })
//       .catch(e => {
//         reject(e)
//       })
//   })
// }

// 文件下载
export function $fileDownLoad (params) {
  return new Promise((resolve, reject) => {
    service({
      url: params.url,
      method: params.method,
      params: params.data,
      responseType: 'blob'
    })
      .then(res => {
        let data = res
        let fileReader = new FileReader()
        fileReader.onload = function () {
          try {
            let jsonData = JSON.parse(this.result)
            if (jsonData.code) {
              // 说明是普通对象数据，后台转换失败
              reject(jsonData)
            }
          } catch (err) {
            if (res instanceof Blob) {
              if (window.navigator.msSaveOrOpenBlob) {
                navigator.msSaveBlob(res, params.filename)
              } else {
                const link = document.createElement('a')
                link.href = window.URL.createObjectURL(res)
                link.download = params.filename
                link.style.display = 'none'
                // 兼容火狐浏览器
                document.body.appendChild(link)
                const evt = document.createEvent('MouseEvents')
                evt.initEvent('click', false, false)
                link.dispatchEvent(evt)
                document.body.removeChild(link)
              }
              resolve({ code: 0 })
            }
          }
        }
        fileReader.readAsText(data)
      })
      .catch(e => {
        reject(e)
      })
  })
}
// 文件下载
export function $fileDownLoad2 (params) {
  return new Promise((resolve, reject) => {
    service({
      url: params.url,
      method: params.method,
      data: params.data,
      responseType: 'blob',
      timeout: params.timeout
    })
      .then(res => {
        let data = res
        let fileReader = new FileReader()
        fileReader.onload = function () {
          try {
            let jsonData = JSON.parse(this.result)
            if (jsonData.code) {
              // 说明是普通对象数据，后台转换失败
              resolve(jsonData)
            }
          } catch (err) {
            if (res instanceof Blob) {
              if (window.navigator.msSaveOrOpenBlob) {
                navigator.msSaveBlob(res, params.filename)
              } else {
                const link = document.createElement('a')
                link.href = window.URL.createObjectURL(res)
                link.download = params.filename
                link.style.display = 'none'
                // 兼容火狐浏览器
                document.body.appendChild(link)
                const evt = document.createEvent('MouseEvents')
                evt.initEvent('click', false, false)
                link.dispatchEvent(evt)
                document.body.removeChild(link)
              }
              resolve({ code: 0 })
            }
          }
        }
        fileReader.readAsText(data)
      })
      .catch(e => {
        reject(e)
      })
  })
}

export default service
